package com.example.demo.controller;

import com.example.demo.DTO.UserRegisterDTO;
import com.example.demo.DTO.UserWebLoginDTO;
import com.example.demo.config.JwtProperties;
import com.example.demo.constant.JwtClaimsConstant;
import com.example.demo.entity.WebUser;
import com.example.demo.result.Result;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtil;
import com.example.demo.vo.UserWebLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/user")
@Tag(name = "用户相关接口")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private JwtProperties jwtProperties;

    /**
     * 用户注册相关接口
     * @param userRegisterDTO
     * @return
     */
    @Operation(summary = "用户注册账号")
    @PostMapping("/register")
    public Result<String> Register(@RequestBody UserRegisterDTO userRegisterDTO){
        if(userService.checkUserExists(userRegisterDTO.getUsername())!=null){
            return Result.error("用户名已经存在");
        }
        else{
            return userService.userRegister(userRegisterDTO);
        }
    }


    /**
     * 网页端登录
     * @param userWebLoginDTO
     * @return
     */
    @Operation(summary="网页端使用账号密码登录")
    @PostMapping("/login")
    public Result<UserWebLoginVO> login(@RequestBody UserWebLoginDTO userWebLoginDTO){
        // 用户登录逻辑
        //1、调用service方法
        if(userService.checkUserExists(userWebLoginDTO.getUsername())==null){
            return Result.error("账号不存在");
        }

        WebUser webUser =userService.webLogin(userWebLoginDTO);
        if(webUser ==null){
            return Result.error("密码错误");
        }

        //2、登录成功后返回jwt令牌
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.WEB_USER_ID, webUser.getId());
        //生成token，注入相关jwtProperties配置属性
        String token= JwtUtil.createJWT(
                jwtProperties.getWebSecretKey(),
                jwtProperties.getWebTtl(),
                claims);

        //3、封装返回结果
        UserWebLoginVO userWebLoginVO = UserWebLoginVO.builder()
                .id(webUser.getId())
                .name(webUser.getName())
                .userName(webUser.getUsername())
                .token(token)
                .build();

        //4、返回结果
        return Result.success(userWebLoginVO);
    }
}
